package com.hup.windowUtil.view;

import com.hup.utils.commons.exception.AppCommonException;
import com.hup.utils.commons.start.DialogHelper;
import com.hup.utils.commons.start.LookThemeUtil;
import com.hup.utils.commons.start.SpringContext;
import com.hup.utils.commons.start.StartupInfo;
import com.hup.utils.swing.frame.BaseFrame;
import com.hup.windowUtil.model.WindowData;
import com.hup.windowUtil.presenter.MainPresenter;
import com.hup.windowUtil.view.customView.WindowItem;
import com.hup.windowUtil.view.customView.WindowItem.SettingActionListener;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.swing.JOptionPane;
import javax.swing.WindowConstants;
import java.awt.GridBagConstraints;

/**
 * @author hugan
 * @date 2021/9/1
 */
@Slf4j
public class MainFrame extends BaseFrame implements SettingActionListener {

    private final MainPresenter presenter;
    private MainForm form;

    public MainFrame() {
        super(StartupInfo.getApplicationChName());
        presenter = SpringContext.getBean(MainPresenter.class);
        initView();
        initListener();
    }

    private void initView() {
        form = new MainForm();
        setContentPane(form.root);

        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setAlwaysOnTop(true);
        LookThemeUtil.initFrameSize(this, 800, 500);
        setLocationRelativeTo(null);
        refreshData();
    }

    private void initListener() {
        form.btnRefresh.addActionListener(e -> refreshData());
        form.cbOnTop.addActionListener(e -> setAlwaysOnTop(form.cbOnTop.isSelected()));
    }

    /**
     * 刷新窗口列表
     */
    private void refreshData() {
        execute("获取窗口信息", presenter::getWindowData, lstWindowData -> {
            int windowCount = lstWindowData.size();
            for (int i = form.pWindow.getComponentCount() - 1; i >= windowCount; i--) {
                form.pWindow.remove(i);
            }
            for (int i = 0; i < windowCount; i++) initItem(i, lstWindowData.get(i));
            form.pWindow.repaint();
        });
    }

    private void initItem(int index, WindowData windowData) {
        int count = form.pWindow.getComponentCount();
        WindowItem windowItem;
        if (index > count - 1) {
            windowItem = new WindowItem(this);
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridx = 0;
            gbc.gridy = index;
            gbc.weightx = 1.0;
            gbc.fill = GridBagConstraints.BOTH;
            form.pWindow.add(windowItem, gbc);
        } else {
            windowItem = (WindowItem) form.pWindow.getComponent(index);
        }
        windowItem.initData(windowData);
    }

    @Override
    public void checkBoxAction(String cmd, boolean selected, WindowData windowData, Runnable failureCallback) {
        doInBackground("修改[" + cmd + "]",
                getExecutor(),
                () -> {
                    switch (cmd) {
                        case WindowItem.CMD_ON_TOP:
                            presenter.setOnTop(windowData, selected);
                            return;
                        case WindowItem.CMD_RESIZE:
                            presenter.setCanResize(windowData, selected);
                            return;
                        case WindowItem.CMD_MAX:
                            presenter.setCanMax(windowData, selected);
                            return;
                    }
                },
                (desc, e) -> {
                    DialogHelper.confirm(e.getMessage())
                            .title(DialogHelper.ERROR)
                            .show(this);
                    failureCallback.run();
                });
    }

    @Override
    public void showResize(WindowData windowData) {
        doInBackground("设置尺寸", () -> {
            presenter.getSize(windowData);
            String res = (String) JOptionPane.showInputDialog(this,
                    windowData.title + "\n尺寸:",
                    "设置尺寸",
                    JOptionPane.PLAIN_MESSAGE,
                    null,
                    null,
                    windowData.width + "," + windowData.height);
            log.info("res={}", res);
            if (StringUtils.isBlank(res)) return;
            try {
                String[] split = res.split(",");
                int width = Integer.parseInt(split[0]);
                int height = Integer.parseInt(split[1]);
                presenter.setSize(windowData, width, height);
            } catch (Exception e) {
                throw new AppCommonException("输入异常? :" + res);
            }
        });
    }
}
